package com.farah.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.farah.lease.common.constant.RedisConstant;
import com.farah.lease.common.exception.LeaseException;
import com.farah.lease.common.result.ResultCodeEnum;
import com.farah.lease.common.utils.JwtUtil;
import com.farah.lease.common.utils.VerifyCodeUtil;
import com.farah.lease.model.entity.UserInfo;
import com.farah.lease.model.enums.BaseStatus;
import com.farah.lease.web.app.service.LoginService;
import com.farah.lease.web.app.service.SmsService;
import com.farah.lease.web.app.service.UserInfoService;
import com.farah.lease.web.app.vo.user.LoginVo;
import com.farah.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-06-25__09:18
 **/
@Service
public class LoginServiceImpl implements LoginService {



    @Autowired
    private SmsService smsService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void getSMSCode(String phone) {
        //验证手机号是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String code = VerifyCodeUtil.getVerifyCode(6);
        smsService.sendCode(phone, code);
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            //若存在,则检查时间
            Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //若存在时间不超过60秒,则抛出异常
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //1.非空验证
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //2.验证码验证
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String RCode = stringRedisTemplate.opsForValue().get(key);
        if (RCode==null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!RCode.equals(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //3.判断用户是否存在
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        //4.判断用户是否被禁
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //5.生成token
        String token = null;
        token = JwtUtil.createToken(userInfo.getId(), phone);
        return token;
    }

    @Override
    public String loginPd(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String password = loginVo.getPassword();
        //1.非空验证
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(password)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PASSWORD_EMPTY);
        }
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (!userInfo.getPassword().equals(password)) {
            throw new LeaseException(ResultCodeEnum.APP_REGISTER_PASSWORD_ERROR);
        }

        //4.判断用户是否被禁
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //5.生成token
        String token = null;
        token = JwtUtil.createToken(userInfo.getId(), phone);
        return token;
    }

    @Override
    public UserInfoVo getUserInfoId(Long userId) {
            UserInfo userInfo = userInfoService.getById(userId);
            return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }

    @Override
    public void register(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String password = loginVo.getPassword();
        //1.非空验证
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if (!StringUtils.hasText(password)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PASSWORD_EMPTY);
        }
        //2.验证码验证
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String RCode = stringRedisTemplate.opsForValue().get(key);
        if (RCode==null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!RCode.equals(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //3.判断用户是否存在,不存在则注册（创建用户）
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setPassword(password);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + phone.substring(6));
            userInfoService.save(userInfo);
        }
    }
}

